<script setup>
import { ref, onMounted,watch } from 'vue';
import { useUserStore } from '@/stores/user'
import { ElDialog, ElMessage, ElMessageBox,ElForm, ElFormItem, ElSelect, ElOption, ElButton  } from 'element-plus'
import { insertCom,getUserList,insertRef,getRanking } from '@/api/user.js'

const userStore = useUserStore();
// 使用 store 中的数据
const userId = userStore.userId;
const userName = userStore.userName;

// 定义一个 ref 来存储 item 对象
const item = ref({});
const userList = ref([])
const collegeList = ref([])
const classList = ref([])
const refList = ref([])
const rankingList = ref([])
const showRankingList = ref(false);  // 用于控制排名列表的显示


onMounted(() => {
  const storedItem = JSON.parse(localStorage.getItem('selectedItem'));
  if (storedItem) {
    item.value = storedItem;
  }
  localStorage.removeItem('selectedItem');
  
  checkEventTime();  // 检查是否显示排名列表
});

watch(
  () => item.value.projectId,
  (newProjectId) => {
    if (newProjectId) {
      list();  
    }
  }
);

// 检查比赛时间是否在当前时间之前
const checkEventTime = () => {
  const eventTime = new Date(item.value.eventTime).getTime();
  const currentTime = new Date().getTime();
  
  if (currentTime > eventTime) {
    showRankingList.value = true;  // 本地时间晚于 eventTime，显示排名列表
  } else {
    showRankingList.value = false; // 本地时间早于 eventTime，不显示排名列表
  }
};

// 获取参赛人员名单
const list = async () => {
  try {
    const resp = await getUserList(item.value.projectId);  // 使用 item.value.projectId
    const response = await getRanking(item.value.projectId)
    rankingList.value = response.data
    // console.log(rankingList.value)
    if (Array.isArray(resp.data.userList)) {  // 检查 resp.data.userList 是否为数组
      userList.value = resp.data.userList;  // 如果是数组，直接赋值给 userList
      collegeList.value = resp.data.collegeList
      classList.value = resp.data.classList
      refList.value = resp.data.refList
      // console.log(collegeList.value)
      // console.log(classList.value)
      // console.log(refList.value)
    } else {
      console.error("返回的数据不是数组", resp.data.userList);
      ElMessage.error("获取名单失败，返回的数据格式不正确");
    }
    console.log(userList.value);
    ElMessage.success("获取名单成功");
  } catch (error) {
    ElMessage.error("获取数据失败");
  }
};


//申请报名
// const handleRegister = async () => {
//     try {
//         await insertCom(item.value,userId)
//         ElMessage.success("报名成功")
//         list()
//     } catch (error){
//         ElMessage.error("人数已达标，期待下次到来")
//     }

// }

const handleRegister = async () => {
  // 检查 userList 中是否已存在 userStore.userName
  const isAlreadyRegistered = userList.value.some(user => user.username === userName);
  const isAlreadyReferee = refList.value.some(ref => ref.username === userName);

  if (isAlreadyRegistered || isAlreadyReferee) {
    // 如果已报名，弹出不可重复报名的提示
    ElMessage.warning("您已报名，请勿重复报名");
  } else {
    // 如果未报名，继续执行报名操作
    try {
      await insertCom(item.value, userId);
      ElMessage.success("报名成功");
      list();  // 重新获取名单
    } catch (error) {
      ElMessage.error("人数已达标，期待下次到来");
    }
  }
};

//申请裁判员
const handleCancel = async () => {

  const isAlreadyRegistered = userList.value.some(user => user.username === userName);
  const isAlreadyReferee = refList.value.some(ref => ref.username === userName);
  if((isAlreadyRegistered || isAlreadyReferee)){
    ElMessage.warning("您已报名，请勿重复报名");
  }else{
    try {
        await insertRef(item.value,userId)
        ElMessage.success("申请成功，请准时到达场地")
        list()
    } catch (error) {
        ElMessage.error("裁判已足够")
    }
  }
}


const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

</script>

<template>
    <el-card class="box-card" shadow="hover">
      <h2 style="text-align: center; margin-bottom: 20px;">比赛信息</h2>
      
      <el-descriptions bordered column={1} class="description-box">
        <el-descriptions-item label="项目名称：">{{ item.name }}</el-descriptions-item>
        <el-descriptions-item label="项目编号：">{{ item.number }}</el-descriptions-item>
        <el-descriptions-item label="规则介绍：">{{ item.introduction }}</el-descriptions-item>
        <el-descriptions-item label="比赛类型：">{{ item.type == 0 ? '个人赛' : '团体赛' }}</el-descriptions-item>
        <el-descriptions-item label="男子/女子：">{{ item.gtype === 0 ? '女子' : '男子' }}</el-descriptions-item>
        <el-descriptions-item label="比赛地点：">{{ item.place }}</el-descriptions-item>
        <el-descriptions-item label="比赛时间：">{{ formatDate(item.eventTime) }}</el-descriptions-item>
        <el-descriptions-item label="招收参赛人员：">{{ item.upnum }} 人</el-descriptions-item>
        <el-descriptions-item label="招收裁判员：">{{ item.renum }} 人</el-descriptions-item>
        <el-descriptions-item label="报名时间：">{{ formatDate(item.startTime) }} -- {{ formatDate(item.endTime) }}</el-descriptions-item>
        <el-descriptions-item>欢迎大家踊跃报名！</el-descriptions-item>
      </el-descriptions>
  
      <div class="actions" style="text-align: center; margin-top: 20px;">
        <el-button 
          type="primary" 
          @click="handleRegister" 
          :disabled="item.status !== 1"
          :style="{ cursor: item.status === 1 ? 'pointer' : 'not-allowed' }">
          报名参加
        </el-button>
        <el-button 
          type="danger" 
          @click="handleCancel" 
          :disabled="item.status !== 1"
          :style="{ cursor: item.status === 1 ? 'pointer' : 'not-allowed' }">
          申请裁判
        </el-button>
      </div>
  
      <!-- 参赛人员列表 -->
      <el-card class="participant-card" shadow="hover" style="margin-top: 30px;">
        <h3 style="text-align: center; margin-bottom: 15px;">参赛人员列表</h3>
        <el-table :data="userList" stripe style="width: 100%">
          <el-table-column prop="username" label="姓名" width="200"></el-table-column>
          
          <!-- 显示学院名称 -->
          <el-table-column label="学院" width="200">
            <template #default="scope">
              <span>
                <span v-for="college in collegeList" :key="college.collegeId">
                  {{ college.collegeId === scope.row.collegeId ? college.name : '' }}
                </span>
              </span>
            </template>
          </el-table-column>
          
          <!-- 显示班级名称 -->
          <el-table-column label="班级" width="150">
            <template #default="scope">
              <span>
                <span v-for="classItem in classList" :key="classItem.classId">
                  {{ classItem.classId === scope.row.classId ? classItem.name : '' }}
                </span>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
  
      <!-- 裁判员列表 -->
      <el-card class="participant-card" shadow="hover" style="margin-top: 30px;">
        <h3 style="text-align: center; margin-bottom: 15px;">裁判员列表</h3>
        <el-table :data="refList" stripe style="width: 100%">
          <el-table-column prop="username" label="姓名" width="200"></el-table-column>
          
          <!-- 显示学院名称 -->
          <el-table-column label="学院" width="200">
            <template #default="scope">
              <span>
                <span v-for="college in collegeList" :key="college.collegeId">
                  {{ college.collegeId === scope.row.collegeId ? college.name : '' }}
                </span>
              </span>
            </template>
          </el-table-column>
          
          <!-- 显示班级名称 -->
          <el-table-column label="班级" width="150">
            <template #default="scope">
              <span>
                <span v-for="classItem in classList" :key="classItem.classId">
                  {{ classItem.classId === scope.row.classId ? classItem.name : '' }}
                </span>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>


      <el-card v-if="showRankingList" class="participant-card" shadow="hover" style="margin-top: 30px;">
      <h3 style="text-align: center; margin-bottom: 15px;">排名列表</h3>
      <el-table :data="rankingList" stripe style="width: 100%">
        <el-table-column prop="username" label="姓名" width="90"></el-table-column>
        <el-table-column label="学院" width="90">
          <template #default="scope">
            <span>
              <span v-for="college in collegeList" :key="college.collegeId">
                {{ college.collegeId === scope.row.collegeId ? college.name : '' }}
              </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="班级" width="100">
          <template #default="scope">
            <span>
              <span v-for="classItem in classList" :key="classItem.classId">
                {{ classItem.classId === scope.row.classId ? classItem.name : '' }}
              </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="result" label="结果" width="100"></el-table-column>
        <el-table-column prop="score" label="分数" width="90"></el-table-column>
        <el-table-column prop="rank" label="名次" width="100"></el-table-column>
      </el-table>
    </el-card>

  
    </el-card>
  </template>

<style lang="scss" scoped>
.box-card {
  max-width: 650px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
}

.description-box {
  background-color: #fff;
  padding: 15px;
  border-radius: 10px;
}

.actions {
  display: flex;
  justify-content: space-around;
}

.el-descriptions__label {
  font-weight: bold;
}

.el-button {
  width: 120px;
}
</style>
